# -*- coding:utf-8 -*-
from functools import wraps
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.db import transaction


class LoginRequired(object):
    """重写as_view()"""

    @classmethod
    def as_view(cls, **initkwargs):
        view = super().as_view()
        return login_required(view)


def login_required_json(view_func):
    """"""
    @wraps(view_func)
    def wrapper(request,*args,**kwargs):
        """判断用户 是否登陆!"""
        if not request.user.is_authenticated():
            return JsonResponse({'code':1,'message':'用户未登陆!'})
        else:
            return view_func(request,*args,**kwargs)
    return wrapper


class LoginRequiredJSONMixin(object):

    @classmethod
    def as_view(cls, **initkwargs):
        view = super().as_view(**initkwargs)
        return login_required_json(view)


class TransactionAtomicMixin(object):

    @classmethod
    def as_view(cls, **initkwargs):
        view = super().as_view(**initkwargs)
        return transaction.atomic(view)